package com.xvyy.tingshu.common.minio.config;

import com.xvyy.tingshu.common.execption.TsException;

import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


/**
 * ClassName: MinioAutoConfiguration
 * Package: com.xvyy.tingshu.common.config.minio
 *
 * @Description: Minio自动配置类
 * @Author: xvyy
 * @Create: 2025/1/14 - 18:47
 * @Version: v1.0
 */
@Configuration
@EnableConfigurationProperties(MinioProperties.class)
@ConditionalOnProperty(prefix = "minio", havingValue = "true", value = "enable")
public class MinioAutoConfiguration {

    Logger logger = LoggerFactory.getLogger(MinioAutoConfiguration.class);

    @Bean
    public MinioClient minioClient(MinioProperties minioProperties) {

        // 抽取配置文件中的属性
        String minioUrl = minioProperties.getEndpointUrl();
        String accessKey = minioProperties.getAccessKey();
        String secretKey = minioProperties.getSecretKey();
        String bucketName = minioProperties.getBucketName();

        // 1. 创建MinIO客户端对象
        MinioClient minioClient =
                MinioClient.builder()
                        .endpoint(minioUrl) // 改成自己的MinIO服务器地址
                        .credentials(accessKey, secretKey) // 改成自己的MinIO账号和密码
                        .build();
        boolean found = false;// 判断桶是否存在
        try {
            // 2. 检查桶是否存在，如果不存在则创建
            found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
            if (!found) {
                logger.info("{}桶不存在，正在创建", bucketName);
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
            } else {
                logger.info("{}桶已经存在，无需创建", bucketName);
            }
            return minioClient;
        } catch (Exception e) {
            // 抛出异常，停止项目启动
            logger.error("minio对象初始化失败：{}", e.getMessage());
            throw new TsException(201, "minio对象初始化失败");
        }
    }


}
